package com.classichu.jetpacksimple.ui.zhihu;

import android.arch.core.util.Function;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.Transformations;
import android.arch.lifecycle.ViewModel;

import com.classichu.jetpacksimple.data.DataRepository;
import com.classichu.jetpacksimple.data.local.entity.ZhihuStory;

import java.util.List;

public class ZhihuViewModel extends ViewModel {

    private DataRepository mDataRepository;
    private static final String REFRESH = "refresh";

    public ZhihuViewModel() {
        mDataRepository = DataRepository.getInstance();
        mZhihuStoryListLiveData = Transformations.switchMap(mZhihuLoadMoreFlagLiveData, new Function<String, LiveData<List<ZhihuStory>>>() {
            @Override
            public LiveData<List<ZhihuStory>> apply(String input) {
                if (REFRESH.equals(input)) {
                    return mDataRepository.getLatestZhihuStoryList();
                }
                //
                return mDataRepository.getBeforeZhihuStoryList();
            }
        });

    }

    private LiveData<List<ZhihuStory>> mZhihuStoryListLiveData;

    public LiveData<List<ZhihuStory>> getZhihuStoryListLiveData() {
        return mZhihuStoryListLiveData;
    }

    private final MutableLiveData<String> mZhihuLoadMoreFlagLiveData = new MutableLiveData<>();

    public void refreshZhihuStoryList() {
        mZhihuLoadMoreFlagLiveData.setValue(REFRESH);
    }

    public void loadMoreZhihuStoryList(String loadMoreFlag) {
        mZhihuLoadMoreFlagLiveData.setValue(loadMoreFlag);
    }

    public LiveData<Boolean> IsLoading() {
        return mDataRepository.IsLoading();
    }
}